package com.zeus.gen.generate.controller;

import com.zeus.gen.base.controller.BaseController;
import com.zeus.gen.base.service.BaseService;
import com.zeus.gen.generate.dto.GenerateDto;
import com.zeus.gen.generate.model.Generate;
import com.zeus.gen.generate.service.GenerateService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * GenerateController
 *
 * @author liuwei
 * @version 2018-08-07 11:05:10
 */
@Controller
@RequestMapping("generate")
public class GenerateController extends BaseController<Generate, GenerateDto> {

    @Autowired
    private GenerateService generateService;

    @Override
    protected String getPrefix() {
        return "generate";
    }

    @Override
    protected BaseService getBaseService() {
        return generateService;
    }

    @RequestMapping(value = "/add/{tableName}", method = RequestMethod.GET)
    public String add(@PathVariable("tableName") String tableName, Model model) {
        model.addAttribute("tableName", tableName);
        return super.add(model);
    }

    /**
     * 生成代码
     */
    @PostMapping("/code")
    public void code(Generate generate, HttpServletResponse response) throws IOException {
        String[] tableNames = new String[]{generate.getTableName()};
        byte[] data = generateService.generateCode(generate, tableNames);

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"zeus-gen-code.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
    }

}